package com.yhy.wxzn.wcs.device.rgv.bean;

import com.yhy.wxzn.wcs.device.rgv.enums.PalletStatus;
import com.yhy.wxzn.wcs.device.rgv.enums.ReversingDirection;
import com.yhy.wxzn.wcs.device.rgv.enums.RunningDirection;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class Fragment {

    //存储一条直线上的节点
    private List<Node> nodes;

    private ReversingDirection reversingDirection;

    private PalletStatus palletStatus;

    //行驶方向（从小车电池方向看过去）1左2右3上4下
    private RunningDirection direct;

    /**
     * 毫米
     */
    //此段的行驶里程
    private int roadHaul;

    /**
     *  cm/s
     */
    //上位机给定运行的速度，默认按照下位机设置的速度
    private int speed;


    public Fragment(List<Node> nodes){
        this.nodes = nodes;
        this.direct = RunningDirection.getDirect(nodes);
        this.reversingDirection = ReversingDirection.getReversingDirection(nodes);
        this.roadHaul = caculRoadHual(nodes);
        this.speed = 35;
    }

    private int caculRoadHual(List<Node> nodes) {
        Node s = nodes.get(0);
        Node e = nodes.get(nodes.size() - 1);

        return s.getX() == e.getX() ? Math.abs(s.getOffsetY() - e.getOffsetY()): Math.abs(s.getOffsetX() - e.getOffsetX());
    }


    public static List<Fragment> buildFragments(List<Node> path){
        List<Fragment> fragments = new ArrayList<>();
        if (path.size() < 2)
            return fragments;


        List<Node> ns = new ArrayList<>();


        if(path.size() == 2){
            ns.addAll(path);
            fragments.add(new Fragment(ns));
            return fragments;
        }

        for (int i = 0; i < path.size() - 2; i++) {
            ns.add(path.get(i));
            //最后三个节点
            if(i + 2 == path.size() - 1){
                if (Node.isStraight(path.get(i),path.get(i + 2))){
                    ns.add(path.get(i + 1));
                    ns.add(path.get(i + 2));

                    fragments.add(new Fragment(ns));
                }else{
                    ns.add(path.get(i + 1));
                    fragments.add(new Fragment(ns));

                    ns = new ArrayList<>();
                    ns.add(path.get(i + 1));
                    ns.add(path.get(i + 2));
                    fragments.add(new Fragment(ns));
                }
            } else if (!Node.isStraight(path.get(i),path.get(i + 2)) ){
                ns.add(path.get(i+1));
                fragments.add(new Fragment(ns));
                ns = new ArrayList<>();
            }
        }

        return fragments;
    }



}
